package com.example.fresh_market.activity;

import android.app.AlertDialog;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;

import com.android.volley.Request;
import com.example.fresh_market.adapter.CreateOrderAdapter;
import com.example.fresh_market.constants.StrConstant;
import com.example.fresh_market.databinding.ActivityCreateOrderBinding;
import com.example.fresh_market.entity.Address;
import com.example.fresh_market.request.ApiResponse;
import com.example.fresh_market.request.CreateOrderResp;
import com.example.fresh_market.request.OrderPrepayResp;
import com.example.fresh_market.request.PreOrderResp;
import com.example.fresh_market.utils.HttpUtil;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;

import org.apache.commons.lang3.StringUtils;

import java.util.ArrayList;
import java.util.Map;

/**
 * 创建订单页面
 */
public class CreateOrderActivity extends AppCompatActivity {

    private ActivityCreateOrderBinding binding;
    private Context mContext;
    private CreateOrderAdapter createOrderAdapter;
    private SharedPreferences preferences;
    private String preOrderNo;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        binding = ActivityCreateOrderBinding.inflate(getLayoutInflater());
        setContentView(binding.getRoot());
        mContext = this;
        RecyclerView orderView = binding.createOrderRecycler;
        orderView.setLayoutManager(new LinearLayoutManager(mContext));
        createOrderAdapter = new CreateOrderAdapter(new ArrayList<>());
        orderView.setAdapter(createOrderAdapter);
        preferences = getSharedPreferences(StrConstant.CONFIG, MODE_PRIVATE);
        initData();
        setEvent();
    }

    private void initData() {
        String preOrderReq = getIntent().getStringExtra("preOrderReq");
        if (StringUtils.isBlank(preOrderReq)) {
            finish();
        }
        HttpUtil.sendJsonRequest(mContext, Request.Method.POST, "/usr/order/pre/order", preOrderReq, response -> {
            Log.d("123", "onCreateView: " + response.toString());
            ApiResponse<PreOrderResp> apiResponse = new Gson().fromJson(response.toString(), new TypeToken<ApiResponse<PreOrderResp>>() {
            }.getType());
            if (apiResponse.getCode() == 200) {
                PreOrderResp orderResp = apiResponse.getData();
                preOrderNo = orderResp.getPreOrderNo();
                createOrderAdapter.setData(orderResp.getProductInfoList());
                binding.totalPrice.setText(String.format("总价：%s", orderResp.getTotalPrice()));
            }
        });
        String token = preferences.getString(StrConstant.TOKEN, "");
        HttpUtil.get(mContext, "/usr/address/default", Map.of(HttpUtil.Auth, token), response -> {
            ApiResponse<Address> apiResponse = new Gson().fromJson(response, new TypeToken<ApiResponse<Address>>() {
            }.getType());
            if (apiResponse.getCode() == 200) {
                Address address = apiResponse.getData();
                binding.addrId.setText(String.format("%s", address.getId()));
                binding.addrName.setText(String.format("%s", address.getRealName()));
                binding.addrPhone.setText(String.format("%s", address.getPhone()));
                binding.addrTitle.setText(String.format("%s-%s-%s", address.getProvince(), address.getCity(), address.getDistrict()));
                binding.addrDetail.setText(String.format("%s", address.getDetail()));
            }
        });
    }

    private void setEvent() {
        binding.addressLayout.setOnClickListener(v -> {
            Intent intent = new Intent(mContext, AddressActivity.class);
            intent.putExtra("createOrder", true);
            startActivityForResult(intent, 777);
        });
        binding.createOrder.setOnClickListener(v -> {
            String addrId = binding.addrId.getText().toString();
            Map<String, String> params = Map.of("preOrderNo", preOrderNo,
                    "payType", "wechat",
                    "shippingType", "1",
                    "addressId", addrId);
            Map<String, String> headers = Map.of(HttpUtil.Auth, preferences.getString(StrConstant.TOKEN, ""));
            HttpUtil.post(mContext, "/usr/order/create",
                    headers,
                    params, response -> {
                        ApiResponse<CreateOrderResp> apiResponse = new Gson().fromJson(response,
                                new TypeToken<ApiResponse<CreateOrderResp>>() {
                                }.getType());
                        if (apiResponse.getCode() == 200) {
                            CreateOrderResp orderResp = apiResponse.getData();
                            HttpUtil.post(mContext, "/usr/order/pre/pay", headers, Map.of("orderId", orderResp.getOrderId()), res -> {
                                ApiResponse<OrderPrepayResp> resp = new Gson().fromJson(response,
                                        new TypeToken<ApiResponse<OrderPrepayResp>>() {
                                        }.getType());
                                if (resp.getCode() == 200) {
                                    AlertDialog.Builder builder = getBuilder();
                                    AlertDialog dialog = builder.create();
                                    dialog.show();
                                }
                            });
                        }
                    });
        });
    }

    private AlertDialog.Builder getBuilder() {
        AlertDialog.Builder builder = new AlertDialog.Builder(mContext);
        builder.setTitle("提示");
        builder.setMessage("支付成功！");
        builder.setPositiveButton("前往首页", (dialog, which) -> {
            Intent intent = new Intent(mContext, MainActivity.class);
            startActivity(intent);
            finish();
        });
        builder.setNegativeButton("回到购物车", (dialog, which) -> {
            finish();
        });
        return builder;
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        if (requestCode == 777 && resultCode == RESULT_OK && data != null) {
            String json = data.getStringExtra("address");
            if (StringUtils.isNotBlank(json)) {
                Address address = new Gson().fromJson(json, Address.class);
                binding.addrId.setText(String.format("%s", address.getId()));
                binding.addrName.setText(String.format("%s", address.getRealName()));
                binding.addrPhone.setText(String.format("%s", address.getPhone()));
                binding.addrTitle.setText(String.format("%s-%s-%s", address.getProvince(), address.getCity(), address.getDistrict()));
                binding.addrDetail.setText(String.format("%s", address.getDetail()));
            }
        }
    }
}
